<template>
  <div class="profile-container">
    <ul v-if="!isEditing" class="profile-display" @dblclick="enterEditMode">
      <li class="avatar-uploader" @click.stop="triggerFileInput">
        <img v-if="userInfo?.avatar" :src="userInfo?.avatar" alt="头像" class="avatar"/>
        <div class="upload-mask">
          <el-icon class="upload-icon">
            <Upload/>
          </el-icon>
          <div class="mask-text">点击修改头像</div>
        </div>
        <input
            type="file"
            ref="fileInput"
            accept="image/*"
            class="file-input"
            @change="handleAvatarUpload"
        />
      </li>

      <li v-if="userInfo"><strong>用户名:</strong> {{ userInfo.username || '未设置' }}</li>
      <li v-if="userInfo"><strong>手机号:</strong> {{ userInfo.phoneNumber || '未设置' }}</li>
      <li v-if="userInfo"><strong>邮箱:</strong> {{ userInfo.email || '未设置' }}</li>
      <li v-if="userInfo"><strong>角色:</strong> {{ roleText(userInfo.role) || '未设置' }}</li>
    </ul>

    <div
        v-else
        class="profile-edit"
        v-click-outside="handleOutsideClick"
    >
      <el-form :model="editedUserInfo" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editedUserInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editedUserInfo.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editedUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editedUserInfo.role" placeholder="请选择角色">
            <el-option label="收件人" value="1"></el-option>
            <el-option label="快递员" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, watch} from 'vue';
import {useStore} from 'vuex';
import {ElMessage} from 'element-plus';
import {Upload} from '@element-plus/icons-vue';
import {uploadAvatar} from "../services/api.js";

const store = useStore();
const userInfo = computed(() => store.getters.userInfo || {});
const isEditing = ref(false);
const editedUserInfo = ref({});
const fileInput = ref(null);
const originalAvatar = ref('');

// 在组件加载时获取用户信息
onMounted(async () => {
  try {
    await store.dispatch('fetchUserInfo'); // 获取用户信息
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
});

// 双击进入编辑模式
const enterEditMode = () => {
  editedUserInfo.value = {...userInfo.value};
  isEditing.value = true;
};

// 点击外部区域处理
const handleOutsideClick = () => {
  if (hasChanges()) {
    saveChanges();
  } else {
    isEditing.value = false;
  }
};

// 检查数据变化
const hasChanges = () => {
  return JSON.stringify(editedUserInfo.value) !== JSON.stringify(userInfo.value);
};

// 保存修改
const saveChanges = async () => {
  try {
    await store.dispatch('updateUserInfo', editedUserInfo.value);
    await store.dispatch('fetchUserInfo'); // 获取用户信息
    ElMessage.success('资料更新成功');
    isEditing.value = false;
  } catch (error) {
    ElMessage.error('资料更新失败');
  }
};

// 头像上传逻辑保持不变
const triggerFileInput = () => {
  fileInput.value.click();
};

const handleAvatarUpload = async (event) => {
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData();
    formData.append('avatar', file);

    try {
      // 调用上传头像的 API
      const response = await uploadAvatar(formData);
      // 上传成功后更新用户信息
      userInfo.value.avatar = response.data; // 假设返回的响应中包含新的头像 URL
      ElMessage.success({message: "头像上传成功", duration: 1000});
    } catch (error) {
      console.error("头像上传失败:", error);
      ElMessage.error({message: "头像上传失败", duration: 1000});
      // 即使上传失败，也显示用户上传的图片
      originalAvatar.value = URL.createObjectURL(file);
    }
  }
};

// 其他逻辑保持不变
const roleText = (role) => {
  const roles = {1: '收件人', 2: '快递员'};
  return roles[role] || '未知角色';
};

// 点击外部指令
const vClickOutside = {
  mounted(el, binding) {
    el.clickOutsideHandler = (e) => {
      if (!el.contains(e.target)) {
        binding.value(e);
      }
    };
    document.addEventListener('click', el.clickOutsideHandler);
  },
  unmounted(el) {
    document.removeEventListener('click', el.clickOutsideHandler);
  }
};
</script>
<style>
.profile-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease-in-out;
}
.profile-display {
  text-align: center;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin-bottom: 1.5rem;
  width: 150px; /* 增大头像尺寸 */
  height: 150px; /* 增大头像尺寸 */
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-uploader:hover {
  transform: scale(1.05);
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f0f0f0;
  transition: all 0.3s ease;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
}

.avatar-uploader:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.mask-text {
  font-size: 14px;
}

.file-input {
  display: none;
}

li {
  font-size: 16px;
  color: #606266;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: left;
  max-width: 400px;
  margin: 1rem auto;
  list-style-type: none; /* 移除默认的列表符号 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

li:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

li strong {
  color: #303133;
  margin-right: 0.5rem;
}

.profile-edit {
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 12px;
}

.el-form-item {
  margin-bottom: 1.5rem;
}

@media (max-width: 768px) {
  .profile-container {
    margin: 1rem;
    padding: 1.5rem;
  }

  .avatar {
    width: 120px;
    height: 120px;
  }

  li {
    font-size: 14px;
    padding: 0.8rem;
  }
}

.el-input.is-active :deep(.el-input__inner) {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.el-form-item:last-child .el-button + .el-button {
  margin-left: 1rem;
}
</style>